package com.hk.api;


import com.hk.api.exceptions.ValidateException;
import com.hk.commons.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Antinomy on 16/10/13.
 */
@Service
public class ValidateService {

    private HttpServletRequest request;

    public ValidateService(HttpServletRequest request) {
        this.request = request;
    }

    public ValidateService() {

    }

    public Object check(String paramName, Object paramValue) {

        if (paramValue ==null)
            handleParamError(paramName);

        return paramValue;
    }

    /**
     * 两个参数不能同时传入
     * @param paramName01
     * @param paramName02
     * @param paramValue01
     * @param paramValue02
     * @return
     */
    public Object checkOneOnly(String paramName01, String paramName02, String paramValue01, String paramValue02) {

        if (StringHelper.isEmpty(paramValue01) && StringHelper.isEmpty(paramValue02))
            handleParamError(paramName01 + "和" + paramName02 + "必须至少传入一个");

        if (StringHelper.isNotEmpty(paramValue01) && StringHelper.isNotEmpty(paramValue02) )
            handleParamError(paramName01 + "和" + paramName02 + "不能同时传入");

        return StringHelper.isNotEmpty(paramValue01)?paramValue01:paramValue02 ;
    }


    public String checkAndPrepare(String paramName, String paramValue) {

        if (StringUtils.isBlank(paramValue))
            handleParamError(paramName);

        return paramValue;
    }

    public Long checkAndPrepareLong(String paramName, String paramValue) {

        if (StringUtils.isBlank(paramValue))
            handleParamError(paramName);

        Long result = null;

        try {
            result = Long.valueOf(paramValue);
        } catch (Exception ex) {
            handleParamError(paramName);
        }

        return result;
    }

    public Integer checkAndPrepareInt(String paramName, String paramValue) {

        if (StringUtils.isBlank(paramValue))
            handleParamError(paramName);

        Integer result = null;

        try {
            result = Integer.valueOf(paramValue);
        } catch (Exception ex) {
            handleParamError(paramName);
        }

        return result;
    }

    private void handleParamError(String errorContext) {
        throw new ValidateException(errorContext);
    }

    private void handleParamOnlyOneError(String errorContext) {
        throw new ValidateException(errorContext);
    }

    /**
     * 检查字段及是否为空
     * @param paramName
     * @param paramValue
     * @return
     */
    public Object checkFieldAndPrepare(String paramName, Object paramValue) {

        if (paramValue ==null) {
            handleParamError(paramName + ":为必要字段");
        }

        if (StringUtils.isBlank(paramValue.toString())) {
            handleParamError(paramName + ":值不能为空");
        }

        return paramValue;
    }

}
